package com.qd.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cdqidi.dto.ApiResult;
import com.cdqidi.dto.ApiResultWrapper;
import com.cdqidi.dto.DelDTO;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.page.PageUtil;
import com.cdqidi.valid.group.DefaultGroup;
import com.cdqidi.valid.group.UpdateGroup;
import com.qd.common.sys.annotation.DataScope;
import com.qd.common.sys.annotation.OperatorInfo;
import com.qd.common.sys.constant.Constants;
import com.qd.common.sys.domain.entity.org.OrgDTO;
import com.qd.common.sys.domain.entity.org.OrgPersonDTO;
import com.qd.common.sys.domain.entity.org.OrgPersonDisplayDTO;
import com.qd.common.sys.enums.OperatorType;
import com.qd.system.service.org.OrgHoldService;
import com.qd.system.service.org.OrgPersonService;
import com.qd.system.service.org.OrgService;
import com.qd.system.treecl.TreeClDTO;
import com.qd.system.treecl.TreeClService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 组织机构信息
 *
 * @author sjk1
 */
@RestController
@Validated
@RequiredArgsConstructor
@Slf4j
public class OrgController {

    private static final String ORG_ID_NULL_MSG = "机构ID不能为空";
    private final OrgService orgService;
    private final OrgHoldService orgHoldService;
    private final OrgPersonService orgPersonService;
    private final TreeClService treeClService;

    /**
     * 新增机构
     */
    @PreAuthorize("@ps.hasPermission('system:org:save')")
    @PostMapping(value = "/sys/sysOrg/save")
    @OperatorInfo(title = "添加组织机构信息", operator = OperatorType.INSERT)
    public ApiResultWrapper<Object> save(@Validated(DefaultGroup.class) @RequestBody OrgDTO orgDTO) {
        if (null == orgDTO.getParentId()) {
            orgDTO.setParentId(Constants.DEFAULT_TREE_PARENT_ID);
        }
        if (null == orgDTO.getAddTime()) {
            orgDTO.setAddTime(LocalDateTime.now());
        }
        return orgService.saveOrg(orgDTO);
    }

    /**
     * 修改机构
     */
    @PreAuthorize("@ps.hasPermission('system:org:edit')")
    @PutMapping(value = "/sys/sysOrg/update")
    @OperatorInfo(title = "修改组织机构信息", operator = OperatorType.UPDATE)
    public ApiResultWrapper<Object> update(@Validated({UpdateGroup.class, DefaultGroup.class}) @RequestBody OrgDTO orgDTO) {
        if (null == orgDTO.getParentId()) {
            orgDTO.setParentId(Constants.DEFAULT_TREE_PARENT_ID);
        }
        if (orgDTO.getParentId().equals(orgDTO.getOrgId())) {
            return ApiResult.error("上级组织机构不能是自己");
        }
        if (null == orgDTO.getUpdateTime()) {
            orgDTO.setUpdateTime(LocalDateTime.now());
        }
        return orgService.updateOrg(orgDTO);
    }

    /**
     * 移动机构信息
     */
    @PreAuthorize("@ps.hasPermission('system:org:move')")
    @PutMapping(value = "/sys/sysOrg/move")
    @OperatorInfo(title = "移动组织机构信息", operator = OperatorType.UPDATE)
    public ApiResultWrapper<Object> move(@Validated @RequestBody OrgDTO orgDTO) {
        if (!StringUtils.hasLength(orgDTO.getOrgId())) {
            return ApiResult.error(ORG_ID_NULL_MSG);
        }
        if (!StringUtils.hasLength(orgDTO.getParentId())) {
            return ApiResult.error("父级ID不能为空");
        }
        if (orgDTO.getOrgId().equals(orgDTO.getParentId())) {
            return ApiResult.error("父级部门相同，不做移动操作");
        }
        if (null == orgDTO.getUpdateTime()) {
            orgDTO.setUpdateTime(LocalDateTime.now());
        }
        return orgService.moveOrg(orgDTO);
    }

    /**
     * 获取机构详细信息
     *
     * @return 机构信息
     */
    @GetMapping(value = "/sys/sysOrg/getById")
    public OrgDTO getById(@Validated @NotBlank(message = ORG_ID_NULL_MSG) String orgId) {
        return orgService.getByIdDto(orgId);
    }

    /**
     * 删除机构信息
     */
    @PreAuthorize("@ps.hasPermission('system:org:delete')")
    @DeleteMapping(value = "/sys/sysOrg/delete")
    @OperatorInfo(title = "删除组织机构信息", operator = OperatorType.DELETE)
    public ApiResultWrapper<Object> delete(@Validated @RequestBody DelDTO<String> delDTO) {
        final List<String> ids = delDTO.getIds();
        if (ids.size() == 1) {
            orgHoldService.deleteByOrgId(ids.get(0));
        } else {
            orgHoldService.deleteByOrgIds(ids);
        }
        return ApiResult.success();
    }

    /**
     * 获取组织机构下拉树列表
     *
     * @return list
     */
    @GetMapping(value = "/sys/sysOrg/treeSelect")
    @DataScope(orgAlias = "org")
    public List<Object> treeSelect(OrgDTO orgDTO) {
        log.info("parentId: {}", orgDTO.getParentId());
        return orgService.treeSelect(orgDTO);
    }

    /**
     * 组织机构列表
     *
     * @return 列表
     */
    @GetMapping(value = "/sys/sysOrg/page")
    @DataScope(orgAlias = "org")
    public IPage<OrgDTO> page(OrgDTO orgDTO) {
        return orgService.page(PageUtil.buildPage(orgDTO), orgDTO);
    }

    /**
     * 刷新组织机构
     *
     * @return 成功
     */
    @PreAuthorize("@ps.hasPermission('system:org:refresh')")
    @GetMapping(value = "/sys/sysOrg/flush")
    @OperatorInfo(title = "重构组织机构", operator = OperatorType.OTHER)
    public ApiResultWrapper<Object> flush() {
        final TreeClDTO treeClDto = orgService.buildTreeClDto();
        treeClService.syncAll(treeClDto);
        treeClDto.freeData();
        return ApiResult.success();
    }

    /**
     * 组织机构导出
     *
     * @param query 查询参数
     */
    @PreAuthorize("@ps.hasPermission('system:org:export')")
    @GetMapping(value = "/sys/sysOrg/export")
    @OperatorInfo(title = "组织机构导出", operator = OperatorType.EXPORT)
    @DataScope(orgAlias = "org")
    public void export(OrgDTO query) throws IOException {
        long startTime = System.currentTimeMillis();
        orgService.export(query);
        long endTime = System.currentTimeMillis();
        log.info("组织机构导出,总耗时: {}s", (endTime - startTime) / 1000);

    }

    /**
     * 机构和人员列表
     *
     * @return 列表
     */
    @GetMapping(value = "/sys/sysOrg/orgPersonPage")
    @DataScope(orgAlias = "sp")
    public IPage<OrgPersonDisplayDTO> orgPersonPage(OrgPersonDTO OrgPersonDTO) {
        if (!StringUtils.hasLength(OrgPersonDTO.getOrgId())) {
            throw new ApiException(ORG_ID_NULL_MSG);
        }
        return orgPersonService.orgPersonPage(PageUtil.buildPage(OrgPersonDTO), OrgPersonDTO);
    }
}